package com.wesley.netty.unpackage;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * CustomMessageDecoder
 *
 * @author WangPanYong
 * @since 2021/11/16 11:00
 */
public class CustomMessageDecoder extends ByteToMessageDecoder {

    int length = 0;
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("CustomMessageDecoder decode 被调用");

        // 需要将得到二进制字节码 -> CustomMessageProtocol 数据包(对象)
        System.out.println(in);

        // 必须大于4个字节
        if (in.readableBytes() >= 4) {
            if (length == 0) {
                length = in.readInt();
            }

            if (in.readableBytes() < length) {
                System.out.println("当前可读数据不够，继续等待。。");
                return;
            }

            byte[] content = new byte[length];
            if (in.readableBytes() >= length) {
                in.readBytes(content);
                //封装成 自定义消息 对象，传递到下一个handler业务处理
                CustomMessageProtocol msg = new CustomMessageProtocol();
                msg.setLen(length);
                msg.setContent(content);
                out.add(msg);
            }
            // 解析完一个数据包，长度归零
            length = 0;
        }
    }

}
